package serviceimpl

import (
	"github.com/RaymondCode/simple-demo/entity/bo"
	"github.com/RaymondCode/simple-demo/entity/param"
	"github.com/RaymondCode/simple-demo/entity/po"
	"github.com/RaymondCode/simple-demo/repository/impl"
	"github.com/RaymondCode/simple-demo/service"
	"sync"
)

type Message struct {
}

func (m Message) SendMessage(messageParam param.Message) error {
	messagePo := po.Message{}
	messagePo.UserId = messageParam.UserId
	messagePo.ToUserId = messageParam.ToUserId
	messagePo.Content = messageParam.Content
	messagePo.CreateTime = messageParam.CreateTime
	return impl.NewMessageDaoInstance().Insert(&messagePo, nil, false)
}

func (m Message) MessageList(messageParam param.Message) (*[]bo.Message, error) {
	messagePo := po.Message{}
	messagePo.UserId = messageParam.UserId
	messagePo.ToUserId = messageParam.ToUserId
	POs, err := impl.NewMessageDaoInstance().QueryByCondition(&messagePo, nil, false)
	if err != nil {
		return nil, err
	}
	var MessageBos []bo.Message
	for _, po := range *POs {
		var bo bo.Message
		bo.UserId = po.UserId
		bo.ToUserId = po.ToUserId
		bo.Content = po.Content
		bo.CreateTime = po.CreateTime
		MessageBos = append(MessageBos, bo)
	}
	return &MessageBos, err
}

var (
	message     service.Message
	messageOnce sync.Once
)

func NewMessageService() service.Message {
	messageOnce.Do(func() {
		message = Message{}
	})
	return message
}
